import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class receive implements Runnable {
    DatagramSocket datagramSocket=null;
    private int port;
    public  receive(int port){
        this.port=port;
        try {
            this.datagramSocket = new DatagramSocket(this.port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while(true){
            try {
                byte[] by=new byte[1024];
                DatagramPacket data = new DatagramPacket(by,0,by.length);
                this.datagramSocket.receive(data);
                int length = data.getLength();  // 获取实际接收到的字节数
                String string = new String(by, 0, length); // 正确的字符串转换
                /*String string = new String(by, 0, length, StandardCharsets.UTF_8);
                别这么写，这么写会导致，打印前面的字符串打印不出来！！！
                */
                System.out.println("receive: " + string);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
